package android.slc.module.user.login

import android.slc.appbase.api.slc.callback.SlcObserver
import android.slc.appbase.repository.remote.DataTransformUtils
import android.slc.appbase.ui.AppViewModel
import android.slc.box.commonlibrary.compat.SlcResourceUtils
import android.slc.box.or.SlcCallbackConfig
import android.slc.module.user.entity.User
import android.slc.module.user.repository.local.sp.AccountSp
import android.slc.module.user.repository.remote.UserServiceRepository
import autodispose2.autoDispose
import javafx.beans.property.SimpleStringProperty
import javafx.beans.property.StringProperty

/**
 * @author slc
 * @date 2022/03/21 下午 3:34
 */
class LoginViewModel : AppViewModel() {
    val accountSp: StringProperty = SimpleStringProperty()
    val passwordSp: StringProperty = SimpleStringProperty()

    companion object {
        const val EVENT_SWITCH_2_MAIN = "switchMainView"
    }

    fun initVm() {
        accountSp.set(AccountSp.getInstance().account)
        passwordSp.set(AccountSp.getInstance().password)
    }

    fun onLogin() {
        UserServiceRepository.login(accountSp.get(), passwordSp.get())
            .map(DataTransformUtils.checkEmpty())
            .to(bindToLifecycle())
            .subscribe(object : SlcObserver<User>(
                SlcCallbackConfig.newBuilder()
                    .setDialogMsg(SlcResourceUtils.getString("user_label_logging"))
                    .setToastRes(SlcResourceUtils.getString("user_label_login_failure"))
                    .build()
            ) {
                override fun onSucceed(data: User) {
                    publish(EVENT_SWITCH_2_MAIN)
                }

                override fun onFailed(errorCode: Int, errorMessage: String?) {
                }
            })

    }
}
